package com.wntime.simulator.device;

import com.wntime.simulator.mapper.MyMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.util.HashMap;
import java.util.Map;

public class SqlDevice {
    private final Simulator simulator;

    public SqlDevice(Simulator simulator) {
        this.simulator = simulator;
    }

    public SqlSessionFactory createSqlSessionFactory() {
        // 创建数据源
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
        dataSource.setUsername("postgres");
        dataSource.setPassword("postgres");
        Configuration configuration = new Configuration();
        configuration.setEnvironment(new Environment(
                "development",
                new JdbcTransactionFactory(),
                dataSource
        ));
        configuration.addMappers("com.wntime.simulator.mapper");
        return new SqlSessionFactoryBuilder().build(configuration);
    }

    public void start() {
        SqlSessionFactory factory = this.createSqlSessionFactory();
        // 使用 SqlSession 进行数据库操作
        SqlSession session = factory.openSession();
        MyMapper mapper = session.getMapper(MyMapper.class);
        Map<String, Object> data = new HashMap<>();
        data.put("id", 2);
        data.put("name", "test");
        data.put("\"10001\"", 20);
        mapper.insertData("abcd",data);
        session.commit();
        session.close();
    }

    public void stop() {

    }

    public static void main(String[] args) {
        SqlDevice  sqlDevice = new SqlDevice(new Simulator());

        sqlDevice.start();
    }
}
